package com.chao.deeply.cas;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author : Rookie
 * @description :
 * @date : 2023/7/5
 */
public class CasABASolve {

    public static void main(String[] args) {
        AtomicStampedReference<Integer> reference = new AtomicStampedReference<>(100, 0);

        // 线程1将值修改为200，再改回100
        Thread thread1 = new Thread(() -> {
            int stamp = reference.getStamp();
            boolean b = reference.compareAndSet(100, 200,stamp,stamp + 1);
            System.out.println("线程1第1次执行cas，是否成功：" + b);
            stamp = reference.getStamp();
            boolean b1 = reference.compareAndSet(200, 100,stamp,stamp + 1);
            System.out.println("线程1第2次执行cas，是否成功：" + b1);
        }, "thread-1");

        // 线程2将值改为300
        Thread thread2 = new Thread(() -> {
            int stamp = reference.getStamp();
            boolean b = reference.compareAndSet(100, 300,stamp,stamp + 1);
            System.out.println("线程2第1次执行cas，是否成功：" + b);
        }, "thread-2");

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终的值：" + reference.getReference());
    }
}
